package com.biubiushop.Socket.NIOChatRoom;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

/**
 * @author chenjia
 * @date 2019/7/16
 **/
public class SocketChannelServer {

    private static final Log log = LogFactory.get();

    private static final String codingType = "gbk";



    public void start() throws IOException {
        //创建selector
        Selector selector = Selector.open();
        //创建channel通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //设置为非阻塞模式
        serverSocketChannel.configureBlocking(false);
        //绑定监听端口
        serverSocketChannel.socket().bind(new InetSocketAddress(9999));
        //将channel注册到selector上
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            //获取channel数量
            int readyChannels = selector.select();
            if (readyChannels == 0) continue;
            //获取可用channel集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            Iterator<SelectionKey> iterator = selectionKeys.iterator();

            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                iterator.remove();

                //根据就绪状态,调用对应方法处理业务逻辑

                //接入事件
                if (selectionKey.isAcceptable()) {
                    log.info("客户端接入服务端");
                    acceptHandler(serverSocketChannel, selector);
                }
                //可读事件
                if (selectionKey.isValid()&&selectionKey.isReadable()) {
                    log.info("客户端与服务端进行读写操作");
                    readHandler(selectionKey);
                }
            }
        }
    }

    //接入事件处理器
    private void acceptHandler(ServerSocketChannel serverSocketChannel, Selector selector) throws IOException {
        //如果是接入事件,创建socketChannel
        SocketChannel socketChannel = serverSocketChannel.accept();
        //设置为非阻塞模式
        socketChannel.configureBlocking(false);

        //将channel注册到selector,监听可读事件
        socketChannel.register(selector, SelectionKey.OP_READ);

        //回复客户端
        socketChannel.write(Charset.forName(codingType).encode("welcome to chatroom!"));

    }


    private void readHandler(SelectionKey selectionKey) throws IOException {
        //从selectionKey中获取已就绪的channel
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();

        //创建buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        //循环读取客户端请求信息
        String request = "";
        try {
            int read = socketChannel.read(byteBuffer);

            if (read > 0) {
                //切换buffer为读模式
                byteBuffer.flip();

                request += Charset.forName(codingType).decode(byteBuffer);
                //将channel再次注册到seletor上,监听可读事件
                Selector selector = selectionKey.selector();
                socketChannel.register(selector, SelectionKey.OP_READ);

                //将客户端发送的信息广播给其他客户端
                if (request.trim().length() > 0) {
                    System.out.println("客户端发送过来的消息为:" + request);
    //            broadCast(selector, socketChannel, request);
                    replyClient(socketChannel, request);
                }

            }else if (read < 0){
                log.info("客户端断开连接");
                socketChannel.close();
                selectionKey.cancel();

            }else {
                log.info("客户端发送空白信息");

            }
        } catch (IOException e) {
            e.printStackTrace();
            socketChannel.close();
            selectionKey.cancel();
        }

//        //将channel再次注册到seletor上,监听可读事件
//        Selector selector = selectionKey.selector();
//        socketChannel.register(selector, SelectionKey.OP_READ);
//
//        //将客户端发送的信息广播给其他客户端
//        if (request.trim().length() > 0) {
//            System.out.println("客户端发送过来的消息为:" + request);
////            broadCast(selector, socketChannel, request);
//            replyClient(socketChannel, request);
//        }
    }

    /**
     * 回复客户端
     *
     */
    private void replyClient(SocketChannel sourceChannel, String request) throws IOException {

        //根据业务返回相应类型
        try {
            sourceChannel.write(Charset.forName(codingType).encode(request));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 广播给其他客户端
     *
     * @param selector
     */
    private void broadCast(Selector selector, SocketChannel sourceChannel, String request) {
        //获取所有已介入的客户端channel
        Set<SelectionKey> selectionKeySet = selector.keys();

        //循环向所有channel广播信息
        selectionKeySet.forEach(selectionKey -> {
            Channel targetChannel = selectionKey.channel();

            if (targetChannel instanceof SocketChannel && targetChannel != sourceChannel) {
                try {
                    ((SocketChannel) targetChannel).write(Charset.forName("utf-8").encode(request));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public static void main(String[] args) throws Exception {
        SocketChannelServer server = new SocketChannelServer();
        server.start();
    }

}
